package com.yulian.util;

import java.nio.charset.StandardCharsets;
import java.util.Arrays;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

import org.apache.commons.codec.binary.Base64;

import com.yulian.web_api.common.CommonManager;

import io.netty.util.internal.logging.InternalLogger;
import io.netty.util.internal.logging.Log4JLoggerFactory; 

public class AESUtils {
	final static InternalLogger logger = Log4JLoggerFactory.getInstance(CommonManager.class);
	private static String ALGORITHM = "AES"; 
	
	/***
	 * 方法1，返回值不对
	 */
	public static String enCode(String key, byte[] content) throws Exception{
        SecretKeySpec skey = new SecretKeySpec(key.getBytes(), "AES");
        Cipher cipher = Cipher.getInstance(ALGORITHM);  //根据指定算法ALGORITHM自成密码器
        cipher.init(Cipher.ENCRYPT_MODE, skey); //初始化密码器，第一个参数为加密(ENCRYPT_MODE)或者解密(DECRYPT_MODE)操作，第二个参数为生成的AES密钥
        byte [] encode_content = cipher.doFinal(content); //密码器加密数据
        return Base64.encodeBase64String(encode_content);
    }

    public static byte[] dnCode(String key,String content){    //content是base64编码字符串
        if (key == null || "".equals(key)) {
            return null;
        }
        if (key.length() != 16) {
            return null;
        }
        try {
            byte [] encode_content = Base64.decodeBase64(content); //把密文字符串转回密文字节数组
            byte[] raw = key.getBytes();  //获得密码的字节数组
            SecretKeySpec skey = new SecretKeySpec(raw, "AES"); //根据密码生成AES密钥
            Cipher cipher = Cipher.getInstance(ALGORITHM);  //根据指定算法ALGORITH生成密码器
            cipher.init(Cipher.DECRYPT_MODE, skey); //初始化密码器，第一个参数为加密(ENCRYPT_MODE)或者解密(DECRYPT_MODE)操作，第二个参数为生成的AES密钥
            return cipher.doFinal(encode_content); //将解密后的数据转换为字符串返回
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }
	/*** end
	 * 方法1，返回值不对
	 */

}
